/*
 * @Author: yanjikun
 * @Date: 2022-03-25 11:30:09
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-06 10:51:46
 * @Description: file content
 */

import { Table, TableProps } from 'ant-design-vue'
import { computed, Slots, unref, watchEffect } from 'vue'
import { DynamicTableProps } from '../dynamic-table'
import { ref } from 'vue'
import { TableColumn } from '../types/column'
import { isBoolean, omit } from 'lodash'

export type Pagination = TableProps['pagination']
export type TableState = ReturnType<typeof useTableState>

export type UseTableStateParams = {
  props: DynamicTableProps
  slots: Slots
}

export const useTableState = ({ props, slots }: UseTableStateParams) => {
  const tableRef = ref<InstanceType<typeof Table>>()
  const loadingRef = ref(!!props.loading)
  const tableData = ref<any[]>([])
  const innerPropsRef = ref<Partial<DynamicTableProps>>()
  const paginationRef = ref<Pagination>(false)
  if (!Object.is(props.pagination, false)) {
    paginationRef.value = {
      current: 1,
      pageSize: 10,
      total: 0,
      pageSizeOptions: ['10', '20', '50', '100'],
      showQuickJumper: true,
      showSizeChanger: true, // 显示可改变每页数量
      showTotal: (total) => `共 ${total} 条`, // 显示总数
      ...props.pagination,
    }
  }
  const getProps = computed(() => ({
    ...props,
    ...unref(innerPropsRef),
  }))
  const getBindValues = computed(() => {
    const props = unref(getProps)
    const columns = (props.columns as TableColumn[]).filter((item) => !item.hideInTable)
    /**是否添加序号 */
    if (props.showIndex) {
      columns.unshift({
        dataIndex: '$$index',
        title: '序号',
        width: 60,
        align: 'center',
        ...props.indexColumnProps,
        bodyCell: ({ index }) => {
          const getPagination = unref(paginationRef)
          if (isBoolean(getPagination)) {
            return <>{`${index + 1}`}</>
          }
          const { current = 1, pageSize = 10 } = getPagination!
          return <>{((current < 1 ? 1 : current) - 1) * pageSize + index + 1}</>
        },
      })
    }
    let propsData: Recordable = {
      ...props,
      columns,
      rowKey: props.rowKey ?? 'id',
      loading: unref(loadingRef),
      tableLayout: 'fixed',
      pagination: unref(paginationRef),
      scroll: {
        y: props.heightAdaptation ? '100%' : undefined,
        ...props.scroll,
      },
    }
    if (slots.expandedRowRender) {
      propsData = omit(propsData, 'scroll')
    }

    propsData = omit(propsData, ['class', 'onChange'])
    return propsData
  })
  // 如果外界设置了dataSource，那就直接用外界提供的数据
  watchEffect(() => {
    if (props.dataSource) {
      tableData.value = props.dataSource
    }
  })
  return { tableRef, loadingRef, tableData, innerPropsRef, getProps, getBindValues, paginationRef }
}
